package com.anti_poverty_detection_system.springboot.controller;

import com.anti_poverty_detection_system.springboot.mapper.TasksMapper;
import com.anti_poverty_detection_system.springboot.model.IdentificationCodes;
import com.anti_poverty_detection_system.springboot.model.Tasks;
import com.anti_poverty_detection_system.springboot.service.ITasksService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ZITONG BAI
 * @since 2024-06-17
 */
@RestController
@RequestMapping("/tasks")
public class TasksController {

    @Autowired
    private ITasksService taskService;
    @Autowired
    private TasksMapper tasksMapper;

    @Value("${upload.path}")
    private String uploadPath; // 文件上传保存路径，配置在application.properties中
    @PostMapping("/save_tasks")
    public ResponseEntity<Integer> saveTasks(@RequestParam("file") MultipartFile file) {
        try {
            // 保存文件到指定目录
            String fileName = file.getOriginalFilename();
            Path filePath = Paths.get(uploadPath).resolve(fileName);

            // 检查文件是否已经存在
            if (Files.exists(filePath)) {
                // 构建 Task 对象并保存文件 URL
                Tasks tasks = new Tasks();
                tasks.setFileUrls(filePath.toString()); // 保存文件的本地路径，也可以保存 URL

                // 保存 Tasks 对象到数据库（这里假设 Tasks 类已经定义）
                taskService.save(tasks);

                // 返回 Tasks 的 ID
                return ResponseEntity.ok(tasks.getTaskId());
            }

            // 文件不存在，保存文件
            Files.copy(file.getInputStream(), filePath);

            // 构建 Task 对象并保存文件 URL
            Tasks tasks = new Tasks();
            tasks.setFileUrls(filePath.toString()); // 保存文件的本地路径，也可以保存 URL

            // 保存 Tasks 对象到数据库（这里假设 Tasks 类已经定义）
            taskService.save(tasks);

            // 返回 Tasks 的 ID
            return ResponseEntity.ok(tasks.getTaskId());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
    @PostMapping("submit_task")
    public ResponseEntity<String> submitTask(@RequestBody Tasks tasks) {
        Tasks tasks1 = taskService.getById(tasks.getTaskId());
        if(tasks1!=null){
            tasks1.setTaskDescription(tasks.getTaskDescription());
            tasks1.setTitle(tasks.getTitle());
            tasks1.setStatus("待完成");
            tasks1.setAssignedBy(tasks.getAssignedBy());
            tasks1.setAssignedTo(tasks.getAssignedTo());
            tasks1.setCreatedAt(LocalDateTime.now());
            tasks1.setUpdatedAt(LocalDateTime.now());
            taskService.saveOrUpdate(tasks1);
            return ResponseEntity.ok().body("任务派发成功");
        }
        else {
            Tasks tasks2 = new Tasks();
            tasks2.setTaskDescription(tasks.getTaskDescription());
            tasks2.setTitle(tasks.getTitle());
            tasks2.setStatus("待完成");
            tasks2.setAssignedBy(tasks.getAssignedBy());
            tasks2.setAssignedTo(tasks.getAssignedTo());
            tasks2.setCreatedAt(LocalDateTime.now());
            tasks2.setUpdatedAt(LocalDateTime.now());
            taskService.saveOrUpdate(tasks2);
            return ResponseEntity.ok().body("任务派发成功");
        }
    }
    @PostMapping("delete_file")
    public ResponseEntity<String> deleteFile(@RequestBody Tasks tasks){
        tasksMapper.deleteById(tasks.getTaskId());
        return ResponseEntity.ok().body("删除文件成功");
    }

    @GetMapping("get_tasks")
    public ResponseEntity<Page<Tasks>> getIdentificationCodes(
            @RequestParam int page,
            @RequestParam int size,
            @RequestParam(required = false) String keywords,
            @RequestParam("assignedBy") String assignedBy
    ) {
        Page<Tasks> tasksPage;
        QueryWrapper<Tasks> queryWrapper =new QueryWrapper<>();

        // 构建查询条件
        if(StringUtils.isNotBlank(assignedBy)){
            queryWrapper.eq("assigned_by",assignedBy);
        }

        // keywords 作为二级查询条件进行模糊搜索
        if (StringUtils.isNotBlank(keywords)) {
            queryWrapper.and(wrapper -> wrapper
                    .like("assigned_to", keywords)
                    .or()
                    .like("title", keywords)
            );
        }
        // 分页查询
        Page<Tasks> pageResult =new Page<>(page,size);
        tasksPage = taskService.page(pageResult,queryWrapper);
        return ResponseEntity.ok().body(tasksPage);
    }
    @PostMapping("get_task_content")
    public ResponseEntity<String> getTaskContent(@RequestBody Tasks tasks){
        Tasks real_task = taskService.getById(tasks.getTaskId());
        return ResponseEntity.ok().body(real_task.getTaskDescription());
    }
    @PostMapping("delete_task")
    public ResponseEntity<String> deleteTask(@RequestBody Tasks tasks){
        tasksMapper.deleteById(tasks.getTaskId());
        return ResponseEntity.ok().body("取消任务成功");
    }
    @PostMapping("/download_file")
    public ResponseEntity<?> downloadFile(@RequestBody Tasks tasks) {
        String url = tasks.getFileUrls();

        if (url == null) {
            return ResponseEntity.badRequest().body("此任务没有文件");
        }

        File file = new File(url);

        if (!file.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("文件不存在");
        }

        try {
            // 获取文件名和扩展名
            String fileName = file.getName();
            String contentType = Files.probeContentType(Paths.get(url));

            InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(contentType));
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentLength(file.length());

            return new ResponseEntity<>(resource, headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件下载失败");
        }
    }
}
